package com.vijay.proxy;

import com.vijay.service.DefaultService;
import com.vijay.service.IUserService;
import com.vijay.service.UserServiceImpl;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;
import java.util.Arrays;

public class ProxyFactoryMain {

    public static void main(String[] args) {

        cglibProxy();
        jdkProxy();

    }

    public static void cglibProxy(){


        DefaultService ds=new DefaultService();
        ProxyFactory pf=new ProxyFactory(ds);

        pf.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                System.out.println("invocation = " + invocation);
                return invocation.proceed();
            }
        });
        DefaultService proxy = (DefaultService)pf.getProxy();
        proxy.sayHello();

    }

    public static void jdkProxy() {
        ProxyFactory pf = new ProxyFactory(new UserServiceImpl());
        pf.addAdvice(new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                Method method = invocation.getMethod();
                if (method.getDeclaringClass() == Object.class) {
                    return method.invoke(this, invocation.getArguments());
                }
                System.out.printf("%s-%s-%s", invocation.getMethod(), Arrays.toString(invocation.getArguments()), invocation.toString());

                return invocation.proceed();
            }
        });

        IUserService userService = (IUserService) pf.getProxy();
        userService.addUser();
        System.out.println(userService.getClass());
    }

}
